package com.scs.application.modules.adm.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.adm.entity.*;
import com.scs.application.modules.adm.mapper.*;
import com.scs.application.modules.adm.service.MatrAuditItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 * 耗材准入汇总单明细 服务实现类
 * </p>
 */
@Service
public class MatrAuditItemServiceImpl extends BaseServiceImpl<MatrAuditItemMapper, MatrAuditItem> implements MatrAuditItemService {
    @Autowired
    private MatrApplyMapper matrApplyMapper;
    @Autowired
    private MatrApplyItemMapper matrApplyItemMapper;
    @Autowired
    private MatrInquiryTargetMapper matrInquiryTargetMapper;
    @Autowired
    private MatrAuditMapper matrAuditMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(Collection<MatrAuditItem> entityList) {
        List<MatrAuditItem> matrAuditItemsSave= new ArrayList<MatrAuditItem>();
        final String[] auditId = {""};
        entityList.forEach(matrAuditItem -> {
            auditId[0] = matrAuditItem.getAuditId();
            if (StringUtils.isBlank(matrAuditItem.getApplyItemId())){ //选择的是申请单
                int count = baseMapper.selectCount(Wrappers.<MatrAuditItem>query().eq("apply_id",matrAuditItem.getApplyId()));
                if (count > 1)  throw new BusinessException("准入申请单【%s】已加入到其他准入审批单中，请移除所选准入申请单号重新提交",matrAuditItem.getApplyBusKey());
                //更新准入申请单状态为院内审核中
                MatrApply matrApply = matrApplyMapper.selectById(matrAuditItem.getApplyId());
                if (!"submit".equals(matrApply.getFlowStatus())) throw new BusinessException("准入申请单【%s】已被科室撤销，请刷新申请单重新选择提交",matrAuditItem.getApplyBusKey());
                List<MatrApplyItem> matrApplyItems =matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("apply_Id",matrAuditItem.getApplyId()).isNull("audit_item_id"));
                if (matrApplyItems ==null || matrApplyItems.size() <1)  throw new BusinessException("准入申请单【%s】的所有明细已加入到其他准入审批单中，请刷新申请单重新选择提交",matrAuditItem.getApplyBusKey());
                matrApplyItems.stream().forEach(matrApplyItem -> {
                    this.beforeSaveCheck(matrApplyItem,matrAuditItem.getAuditId());

                    MatrAuditItem matrAuditItemAdd = new MatrAuditItem();
                    matrAuditItemAdd.setApplyId(matrApplyItem.getApplyId()).setApplyItemId(matrApplyItem.getId()).setAuditId(matrAuditItem.getAuditId());
                    this.save(matrAuditItemAdd);
                    //更新准入申请单明细所关联的审核明细
                    MatrApplyItem matrApplyItemUpdate = new MatrApplyItem();
                    matrApplyItemMapper.update(matrApplyItemUpdate,Wrappers.<MatrApplyItem>update()
                            .eq("id",matrApplyItem.getId())
                            .set("audit_id",matrAuditItemAdd.getAuditId())
                            .set("audit_item_id",matrAuditItemAdd.getId())
                            .set("audit_flow_status_text","制单")
                    );
                });

            } else {//选择的是申请单明细
                MatrApplyItem matrApplyItem = matrApplyItemMapper.selectOne(Wrappers.<MatrApplyItem>query().eq("id",matrAuditItem.getApplyItemId()));
                if (StringUtils.isNotBlank(matrApplyItem.getAuditItemId()))  throw new BusinessException("您所选择的申请明细中有明细已加入到其他准入审批单中，请刷新申请单明细重新选择提交",matrAuditItem.getApplyBusKey());
                this.beforeSaveCheck(matrApplyItem,matrAuditItem.getAuditId());

                MatrAuditItem matrAuditItemAdd = new MatrAuditItem();
                matrAuditItemAdd.setApplyId(matrApplyItem.getApplyId()).setApplyItemId(matrApplyItem.getId()).setAuditId(matrAuditItem.getAuditId());

                this.save(matrAuditItemAdd);
                //更新准入申请单明细所关联的审核明细
                MatrApplyItem matrApplyItemUpdate = new MatrApplyItem();
                matrApplyItemMapper.update(matrApplyItemUpdate,Wrappers.<MatrApplyItem>update()
                        .eq("id",matrApplyItem.getId())
                        .set("audit_id",matrAuditItemAdd.getAuditId())
                        .set("audit_item_id",matrAuditItemAdd.getId())
                        .set("audit_flow_status_text","制单")
                );
            }
        });
//        this.saveBatch(matrAuditItemsSave, 1000);
        this.updateAmount(auditId[0]);
        return true;
    }

    private void beforeSaveCheck(MatrApplyItem matrApplyItem, String auditId){
        //该品名、品规、厂商的耗材是否已添加过
        Integer count = matrApplyItemMapper.selectCount(Wrappers.<MatrApplyItem>query().eq("matr_name",matrApplyItem.getMatrName())
                .eq("matr_spec",matrApplyItem.getMatrSpec())
                .eq("mfg_name",matrApplyItem.getMfgName())
                .eq("audit_id",auditId)
        );
        if (count != null && count > 0) {
            throw new BusinessException("审批明细已添加过同品名名贵厂商的耗材，请重新选择<br>品名:%s<br>品规:%s<br>厂商:%s",
                    matrApplyItem.getMatrName(),
                    matrApplyItem.getMatrSpec(),
                    matrApplyItem.getMfgName());
        }
    }


    /**
    * @Description：审批单合计金凤
    */
    private void updateAmount(String auditId) {
        List<MatrApplyItem> matrApplyItems =matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("audit_id",auditId));
        double amount = 0;
        if (matrApplyItems !=null && matrApplyItems.size()>0) amount = matrApplyItems.stream().mapToDouble(MatrApplyItem::getSkuPrice).sum();

        // 修改请领单总金额
        MatrAudit  matrAudit = new MatrAudit();
        matrAudit.setSkuPriceAmount(amount).setId(auditId);
        matrAuditMapper.updateById(matrAudit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        //更新准入申请表状态为待审核
//        List<MatrApply> matrApplies = matrApplyMapper.selectList(Wrappers.<MatrApply>query().select("id").in("id", idList));
        List<MatrAuditItem> matrAuditItems = baseMapper.selectList(Wrappers.<MatrAuditItem>query().select("apply_item_id,audit_id").in("id", idList));
        matrAuditItems.forEach(matrAuditItem -> {
            //更新准入申请单明细所关联的审核明细
            MatrApplyItem matrApplyItemUpdate = new MatrApplyItem();
            matrApplyItemMapper.update(matrApplyItemUpdate,Wrappers.<MatrApplyItem>update()
                    .eq("id",matrAuditItem.getApplyItemId())
                    .set("audit_id",null)
                    .set("audit_item_id",null)
                    .set("audit_flow_status_text","取消制单")
            );
        });

        //删除供应商询价列表
        matrInquiryTargetMapper.delete(Wrappers.<MatrInquiryTarget>query().in("audit_item_id",idList));
        super.removeCascadeByIds(idList);


        this.updateAmount(matrAuditItems.get(0).getAuditId());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeById(Serializable id){
        return this.removeCascadeByIds(Arrays.asList(id));
    }



    @Override
    public Page<Map> pageForAuditSelectWitchMatr(QueryContext context, Map<String, Object> userParam) {
        return this.baseMapper.pageForAuditSelectWitchMatr(context.getPage(), context.getWrapper(), context.getParams(),userParam);
    }

    @Override
    public Page<Map> pageForAuditSelectWitchMatrAndResult(QueryContext context, Map<String, Object> userParam) {
        return this.baseMapper.pageForAuditSelectWitchMatrAndResult(context.getPage(), context.getWrapper(), context.getParams(),userParam);
    }
}
